package com.ruoyi.diagnosis.service.impl;

import java.util.HashMap;
import java.util.List;

import com.fazecast.jSerialComm.SerialPort;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.diagnosis.domain.Device;
import com.ruoyi.diagnosis.domain.PatientInfo;
import com.ruoyi.diagnosis.listener.MySerialPortEventListener;
import com.ruoyi.diagnosis.service.IPatientInfoService;
import com.ruoyi.diagnosis.util.ModBusCommandUtil;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.diagnosis.domain.Detail;
import com.ruoyi.diagnosis.mapper.ResultMapper;
import com.ruoyi.diagnosis.domain.Result;
import com.ruoyi.diagnosis.service.IResultService;

import javax.annotation.Resource;

/**
 * 扫描结果Service业务层处理
 * 
 * @author fansea
 * @date 2024-07-15
 */
@Service
@Slf4j
public class ResultServiceImpl implements IResultService 
{
    @Autowired
    private ResultMapper resultMapper;

    @Autowired

    @Resource
    private IPatientInfoService patientInfoService ;


    @Autowired
    ISysConfigService configService;

    private Map<String, MySerialPortEventListener> listenerMap = new HashMap<>();
    /**
     * 查询扫描结果
     * 
     * @param id 扫描结果主键
     * @return 扫描结果
     */
    @Override
    public Result selectResultById(Long id)
    {
        return resultMapper.selectResultById(id);
    }

    /**
     * 查询扫描结果列表
     * 
     * @param result 扫描结果
     * @return 扫描结果
     */
    @Override
    public List<Result> selectResultList(Result result)
    {
        return resultMapper.selectResultList(result);
    }

    /**
     * 新增扫描结果
     * 
     * @param result 扫描结果
     * @return 结果
     */
    @Transactional
    @Override
    public int insertResult(Result result)
    {
        result.setCreateTime(DateUtils.getNowDate());
        int rows = resultMapper.insertResult(result);
        insertDetail(result);
        return rows;
    }

    /**
     * 修改扫描结果
     * 
     * @param result 扫描结果
     * @return 结果
     */
    @Transactional
    @Override
    public int updateResult(Result result)
    {
        result.setUpdateTime(DateUtils.getNowDate());
        resultMapper.deleteDetailByFigureId(result.getId());
        insertDetail(result);
        return resultMapper.updateResult(result);
    }

    /**
     * 批量删除扫描结果
     * 
     * @param ids 需要删除的扫描结果主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteResultByIds(Long[] ids)
    {
        resultMapper.deleteDetailByFigureIds(ids);
        return resultMapper.deleteResultByIds(ids);
    }

    /**
     * 删除扫描结果信息
     * 
     * @param id 扫描结果主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteResultById(Long id)
    {
        resultMapper.deleteDetailByFigureId(id);
        return resultMapper.deleteResultById(id);
    }

    @Override
    public String openSerialPort(Device device) {
        //1.1解析设备串口，以及光栅、传送带的地址
        SerialPort serialPort;
        String portName = "COM"+ device.getPort();
        int rasterAddress1 = device.getRasterAddress1();
        int rasterAddress2 = device.getRasterAddress2();
        int[] rasterAddress = {rasterAddress1,rasterAddress2};
        int conveyorAddress = device.getConveyorAddress();
        //1.2串口参数配置
        Integer baudRate = Integer.valueOf(configService.selectConfigByKey("diagnosis.scan.baudRate"));
        Integer dataBits = Integer.valueOf(configService.selectConfigByKey("diagnosis.scan.dataBits"));
        Integer stopBits = Integer.valueOf(configService.selectConfigByKey("diagnosis.scan.stopBits"));
        Integer parity = Integer.valueOf(configService.selectConfigByKey("diagnosis.scan.parity"));
        //2.打开串口，注册监听器
        if (StringUtils.isNotEmpty(portName)) {
            serialPort = ModBusCommandUtil.openPort(portName, baudRate, dataBits, stopBits, parity);
            if (serialPort != null){
                Thread thread = new Thread(() -> {
                    try {
                        MySerialPortEventListener listener = new MySerialPortEventListener(serialPort, 1,rasterAddress,conveyorAddress);
                        listenerMap.put(portName, listener);
                        log.info("添加串口监听器成功");
                    } catch (Exception e) {
                        listenerMap.remove(portName);
                        log.error("添加串口监听器失败", e);
                    }
                });
                thread.start();
            }
        } else {
            serialPort = null;
        }
        return serialPort == null? portName : null;
    }

    @Override
    public void infoEnter(PatientInfo patientInfo) {
        patientInfoService.insertPatientInfo(patientInfo);
        // 加入缓存
    }

    /**
     * 新增历史记录信息
     * 
     * @param result 扫描结果对象
     */
    public void insertDetail(Result result)
    {
        List<Detail> detailList = result.getDetailList();
        Long id = result.getId();
        if (StringUtils.isNotNull(detailList))
        {
            List<Detail> list = new ArrayList<Detail>();
            for (Detail detail : detailList)
            {
                detail.setFigureId(id);
                list.add(detail);
            }
            if (list.size() > 0)
            {
                resultMapper.batchDetail(list);
            }
        }
    }
}
